package cotroller;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.servlet.http.HttpSession;

import model.User;
import service.UserService;
import util.Constant;
import util.Message;
import util.SessionTools;

@ManagedBean
@ViewScoped
public class UserController implements Serializable{

	/**
	 */
	private static final long serialVersionUID = 1L;
	private static User user;
	private Integer id;
	public Integer getId() {
		System.out.println(id+"=========================");
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	UserService us = new UserService();
	
	private List<User> userList;
	
	public List<User> getUserList() {
		userList = us.getList();
		return userList;
	}

	/**提示信息*/
	public String msg;
	
	public String getMsg() {
		return msg;
	}

	public User getUser() {
		if(user == null)
			user = new User();
		
		System.out.println("getUser@"+user);
		return user;
	}

	public String getName(){
		return user.getUsername();
	}
	
	public String login(){
		if(user==null)
			return "login.jsf";
		User u = new User();
		u = us.find(user);
		if(user.getPassword().equals(u.getPassword())){
			HttpSession	session = SessionTools.getSession();
			session.setAttribute(Constant.SESSION_USER, u);
		}
		
		return "index.jsf";
	}
	/**注册*/
	public String sign(){
		if(user == null){
			System.out.println(1);
			Message.setWarnMessage("空用户对象!");
			return "";
			
		}
		if(user.getPassword() == null || user.getUsername() == null){
			System.out.println(1);
			Message.setFatalMessage("用户名和密码不能为空!");
			return "";
		}
		else if(us.find(user)!=null){
			System.out.println(1);
			Message.setErrorMessage("用户名已存在!");
			return "";
		}
		else{
			user.setAddtime(new Date());
			us.add(user);
		}
		return "login.jsf";
	}
	
	public String logout(){
		HttpSession	session = SessionTools.getSession();
		session.setAttribute(Constant.SESSION_USER, null);
		return "login.jsf";
	}
	
	public void deleteById(User u){
		/*System.out.println("========================="+uid);
		user = new User();
		user.setId(uid);
		User u = us.find(user);
		us.delete(u);*/
		user = u;
		System.out.println("delete@"+u);
		//us.delete(user);
		
	}
	
	public String showUser(User u){
		System.out.println("showUser@"+u);
		user = u;
		return "modify.jsf";
	}
	
}
